import page from '../apis/page';
import mode from '../apis/mode';
import { action, observable, observe, toJS } from 'mobx';
import { WeaForm } from 'comsMobx';
import ComponentStore from './form/ComponentStore';
import LeftMenuStore from './form/LeftMenuStore';
import RightMenuStore from './form/RightMenuStore';
import FileUploadStore from './FileUploadStore';
import defaultTheme from '../components/designer/form/theme/styles/default';
import { rm_tabs } from '../constants/form';
import encrypt from '../utils/encrypt';
import { message } from 'antd';
import { WeaLocaleProvider } from 'ecCom';
import ShortCut from './ShortCutStore';

const getLabel = WeaLocaleProvider.getLabel;

export default class FormDesignerStore {
  shortcut = null;
  @observable appid = '';
  @observable saving = false;
  @observable theme = defaultTheme;
  @observable hasSaved = false; // 表单是否保存过 (保存过后即可看见发布的相关信息)
  @observable shortkey = ''; // 页面shortkey 用于表单访问的唯一标识
  @observable isPublishingVisible = false; // 控制发布窗口
  @observable isRuleVisible = false; // 控制规则窗口
  @observable publishSettings = {};// 页面设置信息
  @observable submissionAuthority = [];// 填写权限枚举
  @observable fillinFrequency = [];// 填写票频率枚举
  @observable readonly = false; // 只读权限
  @observable isScriptVisible = false;// 控制代码块弹出
  @observable codeBlock = null;
  @observable tableName = null; // 物理表名
  @observable formTitle = ''; // 表单名称
  @observable joinCube = {
    formmodeId: '',
    options: [],
    isSetCategory: true,
  }; // 关联建模模块
  @observable joinCubeChange = false;
  @observable modeId = null;
  @observable formId = null;
  @observable fileUploadStore = new FileUploadStore();
  @observable form = new WeaForm();
  @observable componentStore = new ComponentStore();
  @observable leftMenuStore = new LeftMenuStore();
  @observable rightMenuStore = new RightMenuStore();
  @observable createLoading = false;
  @observable appParams = {
    superid: 1,
    appid: '',
    addtype: 'addchild',
    name: '',
    desc: '',
    superapp: 1,
    showorder: 0,
    icon: 'icon-coms-ModelingEngine',
    iconColor: '#fff',
    iconBg: '#96358a',
    isInitalModeAndForm: 0,
  };

  @observable modeParams = {
    modeid: '',
    modename: '',
    modetype: 4,
    formid: 0,
    modetitle: '',
    isaddrightbyworkflow: '1',
    id: 0,
    empowmentType: '0,0',
    mode_layoutids: '',
    mode_iscustomorder: '',
    mode_categorytype: '',
  };

  @action init = (appid, readonly) => {
    this.readonly = readonly;
    if (!appid || appid === this.appid) return;

    this.appid = appid;

    this.initWatcher();
    this.leftMenuStore.init();
    this.getJoinCube();
    return this.componentStore.init(appid).then((coms) => {
      this.onHasSavedChange(!!coms.length);
      const { theme, codeBlock = '' } = this.componentStore;
      const formHeader = coms.find(com => com.type === 'FORM_HEADER');

      this.formTitle = formHeader ? formHeader.config.title : '新的表单';
      theme && this.onThemeChange(theme);

      if (codeBlock) {
        this.codeBlock = JSON.parse(codeBlock);
      } else {
        this.codeBlock = { JS: '', CSS: '' };
      }
    });
  }

  @action initShortcut(options) {
    this.shortcut = new ShortCut({
      preventDefault:options.preventDefault
    })
  }

  initWatcher() {
    observe(this.componentStore, 'selectedId', () => {
      const { tabKey, onTabChange } = this.rightMenuStore;

      if (rm_tabs.PROPS !== tabKey) {
        onTabChange(rm_tabs.PROPS);
      }
    });
  }

  @action onEditorValueChange = ([JS, CSS]) => {
    this.codeBlock = { JS, CSS };
  }

  @action saveForm = () => {
    const components = this.componentStore.getComponents(true);

    if (this.saving || this.readonly) return;

    this.saving = true;
    this.setJoinCube();

    let codeBlock = this.codeBlock;

    page.save(this.appid, components, this.theme || '', encrypt.compress(codeBlock)).then((res) => {
      if (res) {
        this.tableName = res.tableName;

        this.componentStore.addFieldNameToCom(res);
        this.componentStore.addDetailTableName(res);
      }

      this.saving = false;
      this.onHasSavedChange(true);
    }).catch(() => {
      this.saving = false;
      this.onHasSavedChange(false);
    });
  }

  @action onThemeChange = (theme) => {
    this.theme = theme;
  }

  @action getPagekey = () => {
    if (this.shortkey) return;

    page.getShortKey(this.appid).then((shortkey) => {
      this.shortkey = shortkey;
    });
  }

  @action getSetInfo = () => {
    page.getSetInfo(this.appid).then((info) => {
      info.startTime = info.startTime ? info.startTime : ' 00:00';
      info.endTime = info.endTime ? info.endTime : ' 00:00';
      this.publishSettings = info;
    });
  }

  @action getSubmissionAuthority = () => {
    if (this.submissionAuthority.length) return;

    page.getSubmissionAuthority().then((data) => {
      this.submissionAuthority = data;
    });
  }

  @action getFillinFrequency = () => {
    if (this.fillinFrequency.length) return;

    page.getFillinFrequency().then((data) => {
      this.fillinFrequency = data;
    });
  }

  @action setUpdate = () => {
    let data = toJS(this.publishSettings);
    data.appid = this.appid;
    Object.keys(data).map((v) => {
      data[v] = data[v] && data[v].toString() ? data[v].toString() : '';
    });
    return page.setUpdate(data);
  }

  @action onSetChange = (key, value) => {
    switch (key) {
      case 'fillinEnabled':
      case 'timeRangeEnabled':
      case 'dataUpperLimitEnabled':
      case 'dailyTimeRangeEnabled':
        value = value === '1';
        break;
      case 'startDate':
      case 'endDate':
        key = key === 'startDate' ? 'startTime' : 'endTime';
        value = `${value} ${this.publishSettings[key].split(' ')[1]}`;
        break;
      case 'startTime':
      case 'endTime':
        value = `${this.publishSettings[key].split(' ')[0]} ${value}`;
        break;
    }
    if (this.publishSettings[key] === value) return;
    this.publishSettings[key] = value;
  }

  @action showPublishingDialog = () => {
    this.isPublishingVisible = true;
  }

  @action showRuleDialog = () => {
    this.isRuleVisible = true;
  }

  @action hidePublishingDialog = () => {
    this.isPublishingVisible = false;
  }

  @action hideRuleDialog = () => {
    this.isRuleVisible = false;
  }

  @action toggleScriptVisible = () => this.isScriptVisible = !this.isScriptVisible;

  onHasSavedChange(ishasSaved) {
    this.hasSaved = ishasSaved;
    ishasSaved && this.getPagekey();
  }

  getJoinCube = () => page.getJoinCube(this.appid).then((data) => {
      this.joinCube = data;
      this.modeId = data.formmodeId;
      this.formId = data.pageId;
      this.pageExpandId = data.pageExpandId;
      this.fileUploadStore.initNames({
        ...data.categoryInfo,
        formId: data.pageId,
        modeId: data.formmodeId,
      });
    })

  setJoinCube = () => {
    const { options, formmodeId } = this.joinCube;
    if (options.length > 0 && this.joinCubeChange) {
      page.setJoinCube(this.appid, JSON.stringify({ formmodeId })).then(() => {
        this.joinCubeChange = false;
      });
    }
  }

  onFormmodeIdChange = (formmodeId) => {
    formmodeId = formmodeId === 'undefined' ? '' : formmodeId;
    const { joinCube } = this;

    joinCube.formmodeId = formmodeId;
    this.modeId = formmodeId;
    this.joinCubeChange = true;
    this.setJoinCube();
    
    if (formmodeId) {
      page.isSetCategory(formmodeId).then((data) => {
        joinCube.isSetCategory = data.isSetCategory;
        this.pageExpandId = data.pageExpandId;
        this.fileUploadStore.initNames({
          ...data.categoryInfo,
          modeId: formmodeId,
        });
      });
    } else {
      joinCube.isSetCategory = true;
    }
  }

  initNames = (obj) => {
    Object.keys(obj).forEach((key) => {
      this[key] = obj[key];
    });
  }

  setFieldName = (name, value) => this[name] = value;

  onSaveMode = (callback) => {
    this.createLoading = true;
    mode.saveApp({
      ...this.appParams,
      name: this.appName,
      fromEDC: 1,
      edcAppid: this.appid
    }).then((res) => {
      mode.saveMode({
        ...this.modeParams,
        modetype: res.appid,
        modename: this.modeName,
        modetitle: this.modeName,
        formid: this.formId,
        fromEDC: 1,
        edcAppid: this.appid
      }).then((res) => {
        if (res.status == '1') {
          message.success(getLabel(501026, '创建成功'));

          this.createLoading = false;
          this.getJoinCube().then(() => {
            this.onFormmodeIdChange(res.id);
            callback();
          });
        }
      });
    });
  }
}
